<template>
  <upload-excel :on-success="onSuccess" />
</template>

<script>
import { importEmployee } from '@/api/employees'
export default {
  components: {

  },
  data() {
    return {

    }
  },
  created() {

  },
  methods: {
    async onSuccess({ header, results }) {
      // console.log(header, results)
      /*
      (1)原始数据
      header = [手机号,姓名,入职日期,转正日期,工号]
      results = [
        {"手机号":13941139879,"姓名":"高大山","入职日期":43535,"转正日期":43719,"工号":20089},
        {"手机号":13941130789,"姓名":"高小山","入职日期":43535,"转正日期":43719,"工号":20099},
        {"手机号":13941119799,"姓名":"高老山","入职日期":43535,"转正日期":43719,"工号":20189}
      ]
      (2)目标数据
      [
        {"mobile":13941139879,"username":"高大山","timeOfEntry":43535,"correctionTime":43719,"workNumber":20089}
      ]
      */
      // 方式1. 第1层通过forEach循环数组,第2层forin循环对象
      /*
      const list = []
      results.forEach(t => {
        const item = {}
        for (var key in t) {
          var newKey = userRelations[key]
          var value = t[key]
          item[newKey] = value
        }
        list.push(item)
      })
      */
      // 方式2. 第1层通过map循环数组,第2层forin循环对象
      /*
      const list = results.map(t => {
        const item = {}
        for (var key in t) {
          var newKey = userRelations[key]
          var value = t[key]
          item[newKey] = value
        }
        return item
      })
      */
      // 方式3. 第1层通过map循环数组,第2层Object.keys(对象)转换成数组,然后forEach循环
      /*
      const list = results.map(t => {
        const item = {}
        Object.keys(t).forEach(key => {
          var newKey = userRelations[key]
          var value = t[key]
          item[newKey] = value
        })
        return item
      })
      */
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const arr = []
      // 方式4取消中间变量
      results.forEach(item => {
        const userInfo = {}
        Object.keys(item).forEach(key => {
          if (userRelations[key] === 'timeOfEntry' || userRelations[key] === 'correctionTime') {
            userInfo[userRelations[key]] = new Date(this.formatDate(item[key], '/'))
            return
          }
          userInfo[userRelations[key]] = item[key]
        })
        arr.push(userInfo)
      })
      await importEmployee(arr)
      this.$message.success('导入成功')
      this.$router.back()
    },
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style lang="less" scoped>

</style>
